/**
 * @file print_tree.c
 * @desc ${DESC} 
 * @author WangBlue(wangjiping596@gmail.com)
 * @date: 2025/10/12 20:39
 * @version: 1.0
 */
#include "print_tree.h"
#include <stdio.h>
#include <stdlib.h>

//=========================
// 栈式打印辅助结构
//=========================
typedef struct Trunk {
    struct Trunk* prev;
    const char* str;
} Trunk;

static Trunk* newTrunk(Trunk* prev, const char* str) {
    Trunk* trunk = (Trunk*)malloc(sizeof(Trunk));
    trunk->prev = prev;
    trunk->str = str;
    return trunk;
}

static void showTrunks(Trunk* p) {
    if (!p) return;
    showTrunks(p->prev);
    printf("%s", p->str);
}

//=========================
// 树打印函数实现
//=========================
static void printTreeHelper(BinNode* node, Trunk* prev, bool isRight) {
    if (!node) return;

    const char* prev_str = "    ";
    Trunk* trunk = newTrunk(prev, prev_str);

    printTreeHelper(node->rChild, trunk, true);

    if (!prev) {
        trunk->str = "———";
    } else if (isRight) {
        trunk->str = "/———";
        prev_str = "   |";
    } else {
        trunk->str = "\\———";
        prev->str = prev_str;
    }

    showTrunks(trunk);
    printf("%d\n", node->data);

    if (prev) prev->str = prev_str;
    trunk->str = "   |";

    printTreeHelper(node->lChild, trunk, false);

    free(trunk);
}

void printTree(BinNode* root) {
    printTreeHelper(root, NULL, false);
}
